package com.polaris.live.ui.live.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.databinding.WidgetCallWaitingBinding
import com.polaris.live.translation.R.string
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * CallWaitingView
 *
 * @author Created by 半仙 on 2023/11/15/015 17:41
 */
class CallWaitingView(context: Context, attributeSet: AttributeSet) :
    FrameLayout(context, attributeSet) {

    private val mBinding = WidgetCallWaitingBinding.inflate(LayoutInflater.from(context), this, true)

    private val textArray = arrayOf("", ".", "..", "...")

    private var mWaitingJob: Job? = null

    init {
        visibility = View.GONE
        mBinding.placeHolding.text =
            "${StringUtils.getString(string.waiting_for_connection)}${textArray[3]}"
    }

    fun initView(viewLifecycleOwner: LifecycleOwner) {
        viewLifecycleOwner.lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                when (event) {
                    Lifecycle.Event.ON_DESTROY -> {
                        mWaitingJob?.cancel()
                        mWaitingJob = null
                    }

                    else -> {}
                }
            }

        })
    }

    fun showWaiting() {
        visibility = View.VISIBLE
        try {
            mWaitingJob = CoroutineScopeManager.ioScope.launch {
                var index = 0
                while (isActive) {
                    withContext(CoroutineScopeManager.mainDispatcher) {
                        mBinding.tvCalling.text =
                            "${StringUtils.getString(string.call_wait_answer)}${textArray[index]}"
                        index = (index + 1) % textArray.size
                        delay(400)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun hideWaiting() {
        visibility = View.GONE

        mWaitingJob?.cancel()
        mWaitingJob = null
    }
}